--------------------------------------------------------------------
-- ROCKET CASINO — Bannière animée en boucle pour CC: Tweaked
-- Thème : Team Rocket (Pokémon) détourné en casino
--
-- PRÉREQUIS : un "Advanced Monitor" (celui qui gère les couleurs)
-- connecté à l'ordinateur qui exécute ce programme.
--
-- Ce que fait la bannière :
--   - Bordure neon qui defile (ampoules de casino)
--   - Grand titre "ROCKET CASINO" (R de Rocket et C de Casino en rouge)
--   - Au centre : la Poke Ball façon Rocket (noir/rouge) qui tourne,
--     en alternance avec un Miaouss (Meowth) qui rigole et rebondit
--   - Bandeau defilant en bas
--------------------------------------------------------------------

-------------------------------
-- CONFIGURATION RAPIDE
-------------------------------
local TEXT_SCALE      = 0.5   -- plus petit = plus de "pixels" disponibles
local FRAME_DELAY      = 0.1   -- vitesse de rafraichissement (secondes)
local ROTATION_SPEED   = 0.22  -- vitesse de rotation de la Poke Ball
local SWITCH_SECONDS   = 4      -- duree d'affichage : Poke Ball <-> Miaouss
local SUBTITLE_TEXT    = "   *** PREPARE FOR TROUBLE * MAKE IT DOUBLE ***   BIENVENUE AU ROCKET CASINO   *** LES JACKPOTS SONT (PRESQUE) GARANTIS ***   "

-------------------------------
-- INITIALISATION DU MONITEUR
-------------------------------
local mon = peripheral.find("monitor")
if not mon then
  error("Aucun moniteur trouve ! Connecte un Advanced Monitor a cet ordinateur.", 0)
end

mon.setTextScale(TEXT_SCALE)
mon.setBackgroundColor(colors.white)
mon.clear()

local W, H = mon.getSize()
if W < 20 or H < 10 then
  print("Astuce : utilise un moniteur plus grand (au moins 3x3 blocs) pour un meilleur rendu.")
end

-------------------------------
-- OUTILS DE DESSIN BAS NIVEAU (canvas pixel + blit)
-------------------------------

local function newCanvas(bg)
  local c = {}
  for y = 1, H do
    c[y] = {}
    for x = 1, W do
      c[y][x] = { bg = bg, ch = " ", fg = colors.white }
    end
  end
  return c
end

local function px(canvas, x, y, bg, ch, fg)
  x, y = math.floor(x + 0.5), math.floor(y + 0.5)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    local cell = canvas[y][x]
    if bg then cell.bg = bg end
    if ch then
      cell.ch = ch
      cell.fg = fg or cell.fg
    end
  end
end

local function render(canvas)
  local toBlit = colors.toBlit
  for y = 1, H do
    local row = canvas[y]
    local chars, fgs, bgs = {}, {}, {}
    for x = 1, W do
      local cell = row[x]
      chars[x] = cell.ch
      fgs[x] = toBlit(cell.fg)
      bgs[x] = toBlit(cell.bg)
    end
    mon.setCursorPos(1, y)
    mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
  end
end

-------------------------------
-- PRIMITIVES DE FORMES
-------------------------------

local function fillEllipse(canvas, cx, cy, rx, ry, color)
  if rx <= 0 or ry <= 0 then return end
  for y = math.floor(cy - ry), math.ceil(cy + ry) do
    local dy = (y - cy) / ry
    local t = 1 - dy * dy
    if t >= 0 then
      local dx = rx * math.sqrt(t)
      for x = math.floor(cx - dx), math.ceil(cx + dx) do
        px(canvas, x, y, color)
      end
    end
  end
end

-- Triangle pointant vers le haut (epines / oreilles)
local function fillTriangleUp(canvas, cx, baseY, tipY, halfWidth, color)
  local height = baseY - tipY
  if height <= 0 then return end
  for y = tipY, baseY do
    local f = (y - tipY) / height
    local w = halfWidth * f
    for x = math.floor(cx - w), math.ceil(cx + w) do
      px(canvas, x, y, color)
    end
  end
end

-- Triangle horizontal (moustaches)
local function fillTriangleSide(canvas, baseX, tipX, cy, halfHeight, color)
  local width = tipX - baseX
  if width == 0 then return end
  local step = width > 0 and 1 or -1
  for x = baseX, tipX, step do
    local f = (x - baseX) / width
    local hh = halfHeight * (1 - f)
    for y = math.floor(cy - hh), math.ceil(cy + hh) do
      px(canvas, x, y, color)
    end
  end
end

-------------------------------
-- MINI POLICE PIXEL 5x7 (pour le grand titre + le "R" de la balle)
-------------------------------

local FONT = {
  R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
  O = { ".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###." },
  C = { ".####", "#....", "#....", "#....", "#....", "#....", ".####" },
  K = { "#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#" },
  E = { "#####", "#....", "#....", "####.", "#....", "#....", "#####" },
  T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
  A = { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" },
  S = { ".####", "#....", "#....", ".###.", "....#", "....#", "####." },
  I = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" },
  N = { "#...#", "##..#", "#.#.#", "#..##", "#...#", "#...#", "#...#" },
}

local function drawGlyph(canvas, pattern, x0, y0, scale, color)
  for row = 1, #pattern do
    local line = pattern[row]
    for col = 1, #line do
      if line:sub(col, col) == "#" then
        for sy = 0, scale - 1 do
          for sx = 0, scale - 1 do
            px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
          end
        end
      end
    end
  end
end

local function drawText(canvas, x, y, text, fg, bg)
  for i = 1, #text do
    px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
  end
end

-------------------------------
-- ÉLÉMENTS DE LA SCÈNE
-------------------------------

-- Bordure "neon" façon enseigne de casino, ampoules qui defilent
local CHASE_COLORS = { colors.yellow, colors.orange, colors.red, colors.orange }
local function drawMarquee(canvas, tick)
  local n = #CHASE_COLORS
  for x = 1, W do
    local c = CHASE_COLORS[((x + tick) % n) + 1]
    px(canvas, x, 1, c)
    px(canvas, x, H, c)
  end
  for y = 1, H do
    local c = CHASE_COLORS[((y + tick) % n) + 1]
    px(canvas, 1, y, c)
    px(canvas, W, y, c)
  end
end

-- Grand titre "ROCKET CASINO" en pixel-art : le R et le C sont rouges,
-- le reste des lettres pulse entre jaune/orange/blanc.
-- Retourne la ligne Y juste sous le titre (pour placer le reste du decor).
local ACCENT_COLORS = { colors.yellow, colors.orange, colors.white, colors.orange }
local function drawBigTitle(canvas, tick)
  local word1, word2 = "ROCKET", "CASINO"
  local LETTER_W, GAP_W, WORD_GAP = 5, 1, 4

  local function wordUnits(word)
    return #word * LETTER_W + (#word - 1) * GAP_W
  end
  local totalUnits = wordUnits(word1) + WORD_GAP + wordUnits(word2)

  local scale = math.max(1, math.floor((W - 6) / totalUnits))
  local totalWidth = totalUnits * scale
  local startX = math.max(2, math.floor((W - totalWidth) / 2) + 1)
  local startY = 3

  local accent = ACCENT_COLORS[(math.floor(tick / 3) % #ACCENT_COLORS) + 1]

  local function drawWord(word, x, redLetterIndex)
    for i = 1, #word do
      local letter = word:sub(i, i)
      local pattern = FONT[letter]
      local color = (i == redLetterIndex) and colors.red or accent
      if pattern then
        -- ombre
        drawGlyph(canvas, pattern, x + 1, startY + 1, scale, colors.black)
        -- lettre
        drawGlyph(canvas, pattern, x, startY, scale, color)
      end
      x = x + (LETTER_W + GAP_W) * scale
    end
    return x
  end

  local cursor = startX
  cursor = drawWord(word1, cursor, 1)              -- "R" de ROCKET en rouge
  cursor = cursor + (WORD_GAP - GAP_W) * scale
  drawWord(word2, cursor, 1)                        -- "C" de CASINO en rouge

  return startY + LETTER_W * 0 + 7 * scale + 2       -- bas du titre + marge
end

-- Bandeau defilant en bas
local function drawSubtitle(canvas, tick)
  local y = H - 2
  local len = #SUBTITLE_TEXT
  local offset = tick % len
  local scrolled = SUBTITLE_TEXT:sub(offset + 1) .. SUBTITLE_TEXT:sub(1, offset)
  local visible = scrolled:sub(1, math.max(0, W - 4))
  drawText(canvas, 3, y, visible, colors.yellow, colors.black)
end

-- Poke Ball animee : palette inversee (noir en haut / rouge en bas) qui tourne
local function drawPokeball(canvas, cx, cy, r, angle)
  local squish = math.max(0.12, math.abs(math.cos(angle)))
  local rx = r * squish
  local ry = r

  fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

  for y = math.floor(cy - ry), math.ceil(cy + ry) do
    local dy = (y - cy) / ry
    local t = 1 - dy * dy
    if t >= 0 then
      local dx = rx * math.sqrt(t)
      local color
      if y < cy - ry * 0.08 then
        color = colors.black
      elseif y > cy + ry * 0.08 then
        color = colors.red
      else
        color = colors.lightGray
      end
      for x = math.floor(cx - dx), math.ceil(cx + dx) do
        px(canvas, x, y, color)
      end
    end
  end

  for x = math.floor(cx - rx), math.ceil(cx + rx) do
    px(canvas, x, cy, colors.black)
  end

  local buttonR = math.max(1, r * 0.28 * squish)
  fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
  fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
  fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

  if squish > 0.55 then
    local scale = math.max(1, math.floor(r * squish / 5))
    drawGlyph(canvas, FONT.R, math.floor(cx - 2 * scale), math.floor(cy - ry * 0.75), scale, colors.red)
  end
end

-- Miaouss stylise (interpretation libre, dessin original) : tete ronde,
-- deux touffes resserrees au centre, pointes laterales, grands yeux ovales,
-- piece sur le front, et une patte qui se leve pour saluer.
local function drawMeowth(canvas, cx, cy, r, phase)
  local bounce = math.sin(phase * math.pi * 2) * r * 0.08
  cy = cy + bounce

  -- burst de rire : les yeux se ferment et la bouche s'ouvre en meme temps
  local laughBurst = math.max(0, math.sin(phase * math.pi * 8))

  -- pointes laterales (2 par cote), fines et radiantes
  fillTriangleSide(canvas, cx - r * 0.85, cx - r * 1.35, cy - r * 0.05, r * 0.05, colors.yellow)
  fillTriangleSide(canvas, cx - r * 0.8, cx - r * 1.25, cy + r * 0.25, r * 0.05, colors.yellow)
  fillTriangleSide(canvas, cx + r * 0.85, cx + r * 1.35, cy - r * 0.05, r * 0.05, colors.yellow)
  fillTriangleSide(canvas, cx + r * 0.8, cx + r * 1.25, cy + r * 0.25, r * 0.05, colors.yellow)

  -- deux touffes resserrees au centre du crane, bout noir
  fillTriangleUp(canvas, cx - r * 0.22, cy - r * 0.55, cy - r * 1.35, r * 0.16, colors.yellow)
  fillTriangleUp(canvas, cx + r * 0.22, cy - r * 0.55, cy - r * 1.35, r * 0.16, colors.yellow)
  fillTriangleUp(canvas, cx - r * 0.22, cy - r * 0.95, cy - r * 1.35, r * 0.09, colors.black)
  fillTriangleUp(canvas, cx + r * 0.22, cy - r * 0.95, cy - r * 1.35, r * 0.09, colors.black)

  -- tete ronde
  fillEllipse(canvas, cx, cy, r, r * 0.95, colors.yellow)

  -- piece d'or sur le front (signe distinctif de Miaouss)
  fillEllipse(canvas, cx, cy - r * 0.55, r * 0.2, r * 0.2, colors.brown)
  fillEllipse(canvas, cx, cy - r * 0.55, r * 0.13, r * 0.13, colors.orange)
  px(canvas, cx, cy - r * 0.62, colors.red)

  -- grands yeux ovales (ouverts), ou fermes/en arc pendant le rire
  if laughBurst > 0.6 then
    for i = -2, 2 do
      px(canvas, cx - r * 0.35 + i, cy - r * 0.08 - math.abs(i) * 0.4, colors.black)
      px(canvas, cx + r * 0.35 + i, cy - r * 0.08 - math.abs(i) * 0.4, colors.black)
    end
  else
    fillEllipse(canvas, cx - r * 0.35, cy - r * 0.12, r * 0.17, r * 0.22, colors.white)
    fillEllipse(canvas, cx + r * 0.35, cy - r * 0.12, r * 0.17, r * 0.22, colors.white)
    fillEllipse(canvas, cx - r * 0.35, cy - r * 0.1, r * 0.1, r * 0.13, colors.lime)
    fillEllipse(canvas, cx + r * 0.35, cy - r * 0.1, r * 0.1, r * 0.13, colors.lime)
    fillEllipse(canvas, cx - r * 0.35, cy - r * 0.08, r * 0.045, r * 0.06, colors.black)
    fillEllipse(canvas, cx + r * 0.35, cy - r * 0.08, r * 0.045, r * 0.06, colors.black)
  end

  -- petit nez rose
  fillEllipse(canvas, cx, cy + r * 0.08, r * 0.06, r * 0.04, colors.pink)

  -- moustaches, fines, sous les yeux
  for _, dy in ipairs({ -0.08, 0, 0.08 }) do
    fillTriangleSide(canvas, cx - r * 0.25, cx - r * 1.1, cy + r * (0.18 + dy), r * 0.02, colors.white)
    fillTriangleSide(canvas, cx + r * 0.25, cx + r * 1.1, cy + r * (0.18 + dy), r * 0.02, colors.white)
  end

  -- bouche : fine par defaut, s'ouvre en grand pendant le rire
  local mouthOpen = r * 0.05 + laughBurst * r * 0.28
  fillEllipse(canvas, cx, cy + r * 0.32, r * 0.22, mouthOpen, colors.red)
  if laughBurst > 0.3 then
    fillEllipse(canvas, cx, cy + r * 0.28, r * 0.1, mouthOpen * 0.5, colors.white)
  end

  -- patte levee qui salue (se leve/s'agite en boucle)
  local wave = math.sin(phase * math.pi * 4)
  local pawX = cx - r * 1.05
  local pawY = cy - r * 0.1 - math.abs(wave) * r * 0.5
  fillEllipse(canvas, pawX, cy + r * 0.55, r * 0.14, r * 0.35, colors.yellow) -- bras
  fillEllipse(canvas, pawX - wave * r * 0.15, pawY, r * 0.16, r * 0.16, colors.yellow) -- patte/main
  px(canvas, pawX - wave * r * 0.15, pawY, colors.brown) -- petit coussinet
end

-------------------------------
-- BOUCLE PRINCIPALE
-------------------------------

local tick = 0
local angle = 0

while true do
  local canvas = newCanvas(colors.black)
  local seconds = tick * FRAME_DELAY

  drawMarquee(canvas, tick)
  local contentTop = drawBigTitle(canvas, tick)

  local centerX = math.floor(W / 2)
  local availableH = math.max(6, (H - 3) - contentTop)
  local centerY = contentTop + math.floor(availableH / 2)
  local shapeR = math.floor(math.min(W * 0.22, availableH * 0.45))

  local showBall = (math.floor(seconds / SWITCH_SECONDS) % 2 == 0)
  if showBall then
    drawPokeball(canvas, centerX, centerY, shapeR, angle)
  else
    local phase = (seconds % SWITCH_SECONDS) / SWITCH_SECONDS
    drawMeowth(canvas, centerX, centerY, shapeR, phase)
  end

  drawSubtitle(canvas, tick)
  render(canvas)

  angle = angle + ROTATION_SPEED
  tick = tick + 1
  sleep(FRAME_DELAY)
end
